<?php
declare(strict_types=1);

namespace Zlf\Mysql\Traits;

use PDOStatement;

trait DataOperator
{

    /**
     * @describe 查询全部数据
     * @param string $sql
     * @param array $binds
     * @return array
     * @user zlf zms-pro@qq.com 2025/1/17
     */
    public function queryAll(string $sql, array $binds = []): array
    {
        return $this->execute($sql, $binds)->fetchAll();
    }

    /**
     * @describe 构造SQL
     * @param string $sql
     * @param array $binds
     * @return PDOStatement
     * @user zlf zms-pro@qq.com 2025/1/17
     */
    protected function execute(string $sql, array $binds = []): PDOStatement
    {
        $stmt = $this->connect()->prepare($sql);
        $stmt->execute($binds);
        return $stmt;
    }

    /**
     * @describe 查询单条数据
     * @param string $sql
     * @param array $binds
     * @return mixed
     * @user zlf zms-pro@qq.com 2025/1/17
     */
    public function queryOne(string $sql, array $binds = []): mixed
    {
        return $this->execute($sql, $binds)->fetch();
    }


    /**
     * @describe 执行
     * @param string $sql
     * @param array $binds
     * @return false|int
     * @user zlf zms-pro@qq.com 2025/1/18
     */
    public function insert(string $sql, array $binds = []): bool|int
    {
        $stmt = $this->connect()->prepare($sql);
        foreach ($binds as $key => $val) {
            $stmt->bindValue($key, $val);
        }
        $res = $stmt->execute();
        if ($res) {
            return $this->connect()->lastInsertId();
        }
        return false;
    }


    /**
     * @describe 执行更新
     * @param string $sql
     * @param array $binds
     * @return int
     * @user zlf zms-pro@qq.com 2025/1/18
     */
    public function update(string $sql, array $binds = []): int
    {
        $stmt = $this->connect()->prepare($sql);
        foreach ($binds as $key => $val) {
            $stmt->bindValue($key, $val);
        }
        $res = $stmt->execute();
        if ($res) {
            return $stmt->rowCount();
        }
        return 0;
    }


    /**
     * @describe 执行删除
     * @param string $sql
     * @param array $binds
     * @return int
     * @user zlf zms-pro@qq.com 2025/1/18
     */
    public function delete(string $sql, array $binds = []): int
    {
        $stmt = $this->connect()->prepare($sql);
        foreach ($binds as $key => $val) {
            $stmt->bindValue($key, $val);
        }
        $res = $stmt->execute();
        if ($res) {
            return $stmt->rowCount();
        }
        return 0;
    }
}